package com.tiantian.app;

import static com.tiantian.app.CommonUtilities.DISPLAY_MESSAGE_ACTION;
import static com.tiantian.app.CommonUtilities.EXTRA_MESSAGE;
import static com.tiantian.app.CommonUtilities.SENDER_ID;
import static com.tiantian.app.CommonUtilities.SERVER_URL;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings.Secure;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;


import com.google.android.gcm.GCMRegistrar;
import com.tiantian.app.R;
import com.infindo.frame.data.DataProcessor;
 
import com.infindo.frame.util.JSONUtil;
import com.infindo.frame.util.ScreenManager;
import com.tiantian.app.activities.*;
import com.tiantian.app.manager.Const;
import com.tiantian.app.manager.DataModel;
import com.tiantian.app.manager.HttpManager;
import com.tiantian.app.manager.LayoutManager;
import com.tiantian.app.manager.ProjDbAdapter;
 

public class MainActivity extends SuperActivity {
   
	private static String TAG = "MainActivity";
	
	
	private final int UPDATE_UI_HANDLER = 1;
	
	private RelativeLayout bootupLayout;
	
	private ImageView logoPartner;
	
	private Drawable logoImage;
	
    AsyncTask<Void, Void, Void> mRegisterTask;
    private int index = 0;
 

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
//		requestWindowFeature(Window.FEATURE_NO_TITLE); // 隐藏标题
//		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); // 设置全屏
        onResetUI();
    }
    
    
    @Override
    public void onResetUI() {
    	// TODO Auto-generated method stub
		setContentView(R.layout.layout_main);
		
		DataModel.DeviceID = Secure.getString(this.getContentResolver(), Secure.ANDROID_ID);
		DataModel.AppID = getPackageName();
		 
		int width  = getWindowManager().getDefaultDisplay().getWidth();
		int height = getWindowManager().getDefaultDisplay().getHeight();
		DataModel.ScreenWidth = width;
		DataModel.ScreenHeight = height;
 
        DataModel.bolLandscape = false;
        if(isTablet(this)){
        	DataModel.bolLandscape = true;
			if(DataModel.ScreenHeight>DataModel.ScreenWidth){
				int tempWidth = DataModel.ScreenWidth;
				DataModel.ScreenWidth = DataModel.ScreenHeight;
				DataModel.ScreenHeight = tempWidth;
				width = DataModel.ScreenWidth;
				height = DataModel.ScreenHeight;
			}
        }
		if(DataModel.bolLandscape){
			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);   
		}else{
			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);   
		}
		Log.e(TAG,"width: "+width+"  height: "+height);
		
		bootupLayout = (RelativeLayout)findViewById(R.id.bootup);
		if(!DataModel.bolLandscape){
			bootupLayout.setBackgroundResource(R.drawable.bootup);
		}
	    findView();
	    setListener();
	    initData();
//	    checkPushSetting();
    }
    
    
	private void checkPushSetting(){
        checkNotNull(SERVER_URL, "SERVER_URL");
        checkNotNull(SENDER_ID, "SENDER_ID");
        // Make sure the device has the proper dependencies.
        try{
        	GCMRegistrar.checkDevice(this);
        }catch(UnsupportedOperationException uoe){
//        	Log.e(TAG,"uoe:"+uoe.getMessage());
        	Toast.makeText(this, "Please install Google Play Store Application first, for using Google Push Service. ", Toast.LENGTH_LONG).show();
        }
 
        
        // Make sure the manifest was properly set - comment out this line
        // while developing the app, then uncomment it when it's ready.
        GCMRegistrar.checkManifest(this);
 
        registerReceiver(mHandleMessageReceiver,new IntentFilter(DISPLAY_MESSAGE_ACTION));
        final String regId = GCMRegistrar.getRegistrationId(this);
        if (regId.equals("")) {
            // Automatically registers application on startup.
            GCMRegistrar.register(this, SENDER_ID);
        } else {
            // Device is already registered on GCM, check server.
            if (GCMRegistrar.isRegisteredOnServer(this)) {
                // Skips registration.
                new Thread(new Runnable() {
                    public void run() {
                    	//always update the register id to server
                    	ServerUtilities.register(getApplicationContext(), regId);
                    }
                }).start();
            } else {
                // Try to register again, but not in the UI thread.
                // It's also necessary to cancel the thread onDestroy(),
                // hence the use of AsyncTask instead of a raw thread.
                final Context context = this;
                mRegisterTask = new AsyncTask<Void, Void, Void>() {

                    @Override
                    protected Void doInBackground(Void... params) {
                        boolean registered =
                                ServerUtilities.register(context, regId);
                        // At this point all attempts to register with the app
                        // server failed, so we need to unregister the device
                        // from GCM - the app will try to register again when
                        // it is restarted. Note that GCM will send an
                        // unregistered callback upon completion, but
                        // GCMIntentService.onUnregistered() will ignore it.
//                        if (!registered) {
//                            GCMRegistrar.unregister(context);
//                        }
                        return null;
                    }

                    @Override
                    protected void onPostExecute(Void result) {
                        mRegisterTask = null;
                    }

                };
                mRegisterTask.execute(null, null, null);
            }
        }
	}
	
    @Override
    protected void onDestroy() {
//        if (mRegisterTask != null) {
//            mRegisterTask.cancel(true);
//        }
//        unregisterReceiver(mHandleMessageReceiver);
//        GCMRegistrar.onDestroy(getApplicationContext());
        super.onDestroy();
    }
	
	
    private void checkNotNull(Object reference, String name) {
        if (reference == null) {
            throw new NullPointerException(
                    getString(R.string.error_config, name));
        }
    }

    private final BroadcastReceiver mHandleMessageReceiver =
            new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);
            Log.e(TAG,"======================  onReceive:"+(index++) +" : "+newMessage);
        }
    };
    
    public boolean isTablet(Context context) {
        boolean xlarge = ((context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == 4);
        boolean large = ((context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE);
//        return (xlarge || large);
        return false;
    }
    
    
    public boolean isTabletDevice() {
        TelephonyManager telephony = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
        int type = telephony.getPhoneType();
        if (type == TelephonyManager.PHONE_TYPE_NONE) {
               DataModel.bolLandscape = true;
        } else {
               DataModel.bolLandscape = false;
        }
        return DataModel.bolLandscape;
    }
    
    
 
	
 
	final Handler handler = new Handler(){
		
		public void handleMessage(Message msg) {
			
			switch(msg.what){
			case UPDATE_UI_HANDLER:
				Intent it = new Intent(MainActivity.this,PageLoginActivity.class);
				startActivity(it);
				ScreenManager.getScreenManager().popActivity(MainActivity.this);
				break;
			}
		};
	};
    
 
 
	@Override
	public void callback(String type, int position, Object obj) {
		// TODO Auto-generated method stub
		if(progressDialog!=null)
			progressDialog.dismiss();

		if(obj == null){
			Toast.makeText(this, "Please check your network first. ", Toast.LENGTH_SHORT).show();
		}
		Log.e(TAG,"type:"+type+"   obj:"+obj);

	}
 
	
 
	
	 

	/* (non-Javadoc)
	 * @see com.infindo.onemalaysia.activities.SuperActivity#findView()
	 */
	@Override
	public void findView() {
		// TODO Auto-generated method stub
		logoPartner = (ImageView)findViewById(R.id.logoParnter);
	}

	/* (non-Javadoc)
	 * @see com.infindo.onemalaysia.activities.SuperActivity#initData()
	 */
	@Override
	public void initData() {
		// TODO Auto-generated method stub
        new Thread(){
        	public void run() {
        		try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
                handler.sendEmptyMessage(UPDATE_UI_HANDLER);
        	}
        }.start();
	}

	/* (non-Javadoc)
	 * @see com.infindo.onemalaysia.activities.SuperActivity#setListener()
	 */
	@Override
	public void setListener() {
		// TODO Auto-generated method stub
		
	}

 
}